package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.CollectDTO;
import com.huaxin.common.Entity.CollectData;
import com.huaxin.common.Entity.EquipmentDTO;
import com.huaxin.common.Entity.IntInfo;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.pulltorefresh.CustomHeaderLayout;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.dialog.HxSetFacilityControlDialog;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/2/1
 * @Desc $desc$
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class  HxCollectActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2 {
    @BindView(R.id.toolbar)
    Toolbar                   mToolbar;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;

    RecyclerView rv_collect;

    public View                emptyView;
    public CollectDatasAdapter mAdapter;
    public List<CollectData> collectDatas = new ArrayList<>();
    private HxSetFacilityControlDialog mControlDialog;
    // private ProgressDialog             dialog;

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_collect;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        if (UserManager.getPlatformName() != null && !UserManager.getPlatformName().isEmpty()) {
            mToolbar.setTitle(UserManager.getPlatformName());
        } else {
            mToolbar.setTitle(UserManager.getOrgName());
        }
        setSupportActionBar(mToolbar);
        pullView.setHeaderLayout(new CustomHeaderLayout(this));
        pullView.setOnRefreshListener(this);
        rv_collect = pullView.getRefreshableView();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        mAdapter = new CollectDatasAdapter(R.layout.collect_item, collectDatas);
        rv_collect.setAdapter(mAdapter);
        rv_collect.setLayoutManager(manager);

        //        dialog = new ProgressDialog(this);
        //        dialog.setMessage("请稍等...");
        //        dialog.setCanceledOnTouchOutside(false);
        //        dialog.setCancelable(false);

        //空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_nodata_center, (ViewGroup) rv_collect.getParent(), false);


        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, final int i) {
                final CollectData collectData = collectDatas.get(i);
                switch (view.getId()) {
                    case R.id.tv_run_data:
                        // 查看运行记录
                        Intent intent = new Intent(HxCollectActivity.this, HxCollectRunStataActivity.class);
                        intent.putExtra(Constant.EQUIPMENTID, collectData.getEquipId());
                        startActivity(intent);

                        break;
                    case R.id.tv_romote_control:
                        //远控设备
                        if (collectData.isRefresh){
                            ToastUtil.showToast("当前正在刷新设备状态，请稍等");
                            return;
                        }
                        if (collectData.getStatus() == 0 || collectData.getStatus() == 2) {
                            //0开启状态 2关闭状态 输入密码
                            //控制类型（1：开操作 2：关操作）controlType
                            //    if(mControlDialog==null){
                            mControlDialog = new HxSetFacilityControlDialog(HxCollectActivity.this, collectData.getEquipId(), new HxSetFacilityControlDialog.OnItemClickListener() {
                                @Override
                                public void onItemClick(String paswd) {
                                    //控制类型（1：开操作 2：关操作）controlType
                                    setPasWdToFacility(paswd, (collectData.getStatus() == 0) ? 2 : 0, collectData.getEquipId(), i);
                                }
                            });
                            //   }
                            mControlDialog.show();
                            if (collectData.getStatus() == 0) {
                                mControlDialog.setTitleText("是否关闭" + collectData.getEquipId());
                            } else {
                                mControlDialog.setTitleText("是否开启" + collectData.getEquipId());
                            }

                        } else {
                            ToastUtil.showToast("当前状态无法远控设备");
                        }
                        break;
                }
            }
        });
    }

    @Override
    protected void requestData() {
        //app/findEquList
        apiFindEquList(null);

    }

    Handler mHandler = new Handler();

    /**
     * 验证密码 远控设备
     *
     * @param paswd
     * @param controlType
     * @param equipId
     */
    private void setPasWdToFacility(String paswd, int controlType, final String equipId, final int position) {
        Call<BaseDTO> pass = HxTransmitRequestHelper.getRequestApi().getRemoteControl(equipId, controlType, paswd);
        pass.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO body = response.body();
                if (response.isSuccessful() && body != null) {
                    if (body.getState() == 1) {
                        //更改设备状态
                        //TODO 弹出进度条 获取当前设备的状态
                        CollectData collectData = collectDatas.get(position);
                        collectData.setRefresh(true);
                        Log.i("lwjing", "刷新单个条目：" + collectData.isRefresh);
                        mAdapter.notifyItemChanged(position);

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                apiFindEquipmentState(equipId, position);
                            }
                        }, 4000);

                    } else {
                        ToastUtil.showToast(body.getMsg());
                    }
                } else {
                    ToastUtil.showToast("操作失败");
                }

                if (mControlDialog != null && mControlDialog.isShowing()) {
                    mControlDialog.cancel();
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast(t.getMessage());
                if (mControlDialog != null && mControlDialog.isShowing()) {
                    mControlDialog.cancel();
                }
            }
        });
    }

    //public int requestNo;

    /**
     * 获取某个设备的状态
     *
     * @param equipId
     * @param position
     */
    private void apiFindEquipmentState(final String equipId, final int position) {
        Call<EquipmentDTO> call = HxTransmitRequestHelper.getRequestApi().getFindEquipmentState(equipId);
        autoClose(call);
        call.enqueue(new Callback<EquipmentDTO>() {
            @Override
            public void onResponse(Call<EquipmentDTO> call, Response<EquipmentDTO> response) {
                EquipmentDTO body = response.body();
                if (response.isSuccessful() && body != null) {
                    IntInfo intInfos = body.getData();
                    CollectData collectData = collectDatas.get(position);
                    Log.i("lwjing", "data[0]=" + intInfos.getStatus() + "collectData status=" + collectData.getStatus());
                    if (intInfos != null) {
                        //开关状态
                        int status = intInfos.getStatus();

                        if ((status == 0 || status == 2) && collectData.getStatus() == status) {
                            //TODO 继续请求
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Log.e("lwjing", "requestNo=");
                                    apiFindEquipmentState(equipId, position);
                                }
                            }, 4000);

                            return;
                        } else {
                            //更新设备状态
                            collectData.setRefresh(false);
                            collectData.setStatus(intInfos.getStatus());
                            mAdapter.setNewData(collectDatas);
                        }
                    }

                    ToastUtil.showToast(body.getMsg());

                } else {

                    //异常返回
                    ToastUtil.showToast("操作失败");

                }
            }

            @Override
            public void onFailure(Call<EquipmentDTO> call, Throwable throwable) {
                Log.e("lwjing", "apiFindEquipmentState onFailure:" + throwable.toString());

                //可能操作成功，但接口请求失败
                ToastUtil.showToast("操作失败");
            }
        });
    }

    /**
     * 获取所有设备 采集数据的状态
     */
    private void apiFindEquList(final PullToRefreshBase refreshView) {
        if (refreshView == null)
            updateLoadStatus(LOADING);
        Call<CollectDTO> call = HxTransmitRequestHelper.getRequestApi().getFindEquList();
        autoClose(call);
        call.enqueue(new Callback<CollectDTO>() {

            @Override
            public void onResponse(Call<CollectDTO> call, Response<CollectDTO> response) {
                CollectDTO runStataDTO = response.body();
                if (response.isSuccessful() && runStataDTO != null) {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_SUCCESS);
                    } else {
                        refreshView.onRefreshComplete();
                    }

                    List<CollectData> collectDataList = runStataDTO.getData();
                    if (collectDataList != null && collectDataList.size() > 0) {
                        Log.i("lwjing", "collectDataList  size: " + collectDataList.size());
                        //数据初始化
                        collectDatas.clear();
                        collectDatas.addAll(collectDataList);
                        mAdapter.setNewData(collectDatas);
                    } else {
                        //设置null布局
                        mAdapter.setEmptyView(emptyView);
                    }

                } else {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_ERROR);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                }
            }

            @Override
            public void onFailure(Call<CollectDTO> call, Throwable t) {
                if (refreshView == null) {
                    updateLoadStatus(LOAD_FAILURE);
                } else {
                    refreshView.onRefreshComplete();
                }
            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        apiFindEquList(refreshView);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        refreshView.onRefreshComplete();
    }

    class CollectDatasAdapter extends BaseQuickAdapter<CollectData, BaseViewHolder> {


        public CollectDatasAdapter(int layoutResId, @Nullable List<CollectData> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, CollectData collectData) {
            TextView tv_device_name = baseViewHolder.getView(R.id.tv_device_name);
            TextView tv_station_name = baseViewHolder.getView(R.id.tv_station_name);
            TextView tv_run_data = baseViewHolder.getView(R.id.tv_run_data);
            TextView tv_stata = baseViewHolder.getView(R.id.tv_stata);
            TextView tv_romote_control = baseViewHolder.getView(R.id.tv_romote_control);
            ProgressBar item_pb = baseViewHolder.getView(R.id.item_pb);


            tv_device_name.setText("设备名称" + collectData.getEquipId());
            tv_station_name.setText("站点：" + collectData.getStationName());

            if (collectData.isRefresh) {
                item_pb.setVisibility(View.VISIBLE);
                tv_romote_control.setClickable(false);
            } else {
                item_pb.setVisibility(View.GONE);
                tv_romote_control.setClickable(true);
            }

            //设备状态 （ 0：正常工作， 1：故障 ， 2：关闭 ，3：断电 ，4：连接超时）
            if (collectData.getStatus() == 0) {
                tv_stata.setText("开启");
                tv_stata.setTextColor(getResources().getColor(R.color.normal));
                if (collectData.isRefresh) {
                    tv_romote_control.setBackgroundResource(R.color.bt_gray);
                } else {
                    tv_romote_control.setBackgroundResource(R.color.blue_button);
                }


            } else if (collectData.getStatus() == 1) {
                tv_stata.setText("故障");
                tv_stata.setTextColor(getResources().getColor(R.color.exception));
                tv_romote_control.setBackgroundResource(R.color.bt_gray);

            } else if (collectData.getStatus() == 2) {
                tv_stata.setText("关闭");
                tv_stata.setTextColor(getResources().getColor(R.color.close));
                if (collectData.isRefresh) {
                    tv_romote_control.setBackgroundResource(R.color.bt_gray);
                } else {
                    tv_romote_control.setBackgroundResource(R.color.blue_button);
                }

            } else if (collectData.getStatus() == 3) {
                tv_stata.setText("断电");
                tv_stata.setTextColor(getResources().getColor(R.color.outage));
                tv_romote_control.setBackgroundResource(R.color.bt_gray);

            } else if (collectData.getStatus() == 4) {
                tv_stata.setText("连接超时");
                tv_stata.setTextColor(getResources().getColor(R.color.outtime));
                tv_romote_control.setBackgroundResource(R.color.bt_gray);

            }
            baseViewHolder.addOnClickListener(R.id.tv_run_data);
            baseViewHolder.addOnClickListener(R.id.tv_romote_control);

        }
    }
}
